﻿using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace 网络加密流实现
{
    class Program
    {
        static int PORT = 10110;
        static void serv()
        {
            TcpListener tcpl = new TcpListener(PORT);
            tcpl.Start();
            var sock = tcpl.AcceptSocket();
            Console.WriteLine("[server]: 启动");

            TLSStream encnet = new TLSStream(sock);
            byte[] buffer = Encoding.UTF8.GetBytes("12345678901234567890");
            encnet.Write(buffer,0, buffer.Length);
            encnet.Flush();
            Console.WriteLine("[server]: 关闭");
            encnet.Close();

            tcpl.Stop();
        }
        static void clie()
        {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sock.Connect(new IPEndPoint(IPAddress.Loopback, PORT));
            Console.WriteLine("[client]: 启动");
            TLSStream encnet = new TLSStream(sock);
            byte[] buffer = new byte[20];
            encnet.Read(buffer, 0, 20);
            Console.WriteLine(Encoding.UTF8.GetString(buffer));
            Console.WriteLine("[client]: 关闭");
            encnet.Close();
        }
        static void Main(string[] args)
        {
            var serverThread = startThread(serv);
            var clientThread = startThread(clie);

            clientThread.Join();
            serverThread.Join();
            Console.ReadLine();
        }
        static Thread startThread(ThreadStart func)
        {
            Thread t = new Thread(func);
            t.Start();
            return t;
        }
    }
}
